import os

import jwt
import time
import hashlib
import base64
import uuid
import hmac
import pymysql
from datetime import datetime

def factory_connection(factory_code):
     return pymysql.connect(host = 'localhost',user = 'admin',passwd = 'ZI94PIQJesVjQhC9OQYR',db = f"lk_{factory_code}",port = 3319)

def waterfall_connection():
    return pymysql.connect(host = 'localhost',user = 'ro',passwd = 'r68y7onNXn5AUo1cL6GXikYRhKWGPr98',port = 3328)





def write_to_file(file_path,factory_code, barcode):
    csv_file_path = os.path.expanduser(file_path)
    os.makedirs(os.path.dirname(csv_file_path), exist_ok=True)
    with open(csv_file_path, "a") as file:
        file.write(f"{factory_code}\t{barcode}\n")


def close_connection(connection):
    if connection:
       connection.close()

def get_ticket_id(factory_code, order_no,channel_code):
    connection = factory_connection(factory_code)

    cursor = connection.cursor()

    cursor.execute(f"SELECT id FROM tkt_ticket WHERE channel_ticket_id = {order_no} and channel_id = (SELECT id FROM sys_channel where `code` = '{channel_code}')")

    results = cursor.fetchall()

    if results:
        first_tuple = results[0]
        result_string = first_tuple[0]
        print(f"{order_no}: {result_string}")
    else:
        result_string = None
        print('查询结果为空')
    close_connection(connection)
    return result_string


def get_fcodebyorder(order_no,channel_code):
    connection = waterfall_connection()

    cursor = connection.cursor()

    cursor.execute(f'SELECT `code` FROM {channel_code}_factory.fty_factory WHERE id = (SELECT factory_id FROM {channel_code}_order.ffl_pickup WHERE order_no = "{order_no}" LIMIT 1)')

    results = cursor.fetchall()

    if results:
        first_tuple = results[0]
        result_string = first_tuple[0].lower()
        print(f"{order_no}: {result_string}")
    else:
        result_string = None
        print('查询结果为空')
    close_connection(connection)
    return result_string

def get_fcodebyticket(order_no,channel_code):

    connection = waterfall_connection()

    cursor = connection.cursor()

    cursor.execute(f'SELECT `code` FROM {channel_code}_factory.fty_factory WHERE id = (SELECT factory_id FROM {channel_code}_ticket.tkt_ticket WHERE id = {order_no})')

    results = cursor.fetchall()

    if results:
        first_tuple = results[0]
        result_string = first_tuple[0]
        print(f"{order_no}: {result_string}")
    else:
        result_string = None
        print('查询结果为空')
    close_connection(connection)
    return result_string





def create_token():
    user_info = {
        "sub": "ohVWb6B9zVZrYbtRwl1GheV-eCY",
        "user": {
            "userId": 99,
            "userName": "数据处理",
            "nickName": "数据处理",
            "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epysJPg0zia43vRPuatZrk9Bd0MZy9xkOnNicHA5T0vjxgZYFANTdJZUHB4oxcGHw4A5Qr8f7KbibvLw/132",
            "roles": [
                {
                    "roleId": 100,
                    "roleName": "管理员",
                    "roleKey": "admin",
                    "roleSort": 1
                },
                {
                    "roleId": 101,
                    "roleName": "操作员",
                    "roleKey": "common",
                    "roleSort": 2
                }
            ]
        },
        "iat": int(time.time()),
        "exp": int(time.time()) + 86400  # Token 有效期为 1 天
    }

    secret_key = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzascdjklkrtyuabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzascdjklkrtyu"

    token = jwt.encode(user_info, secret_key, algorithm='HS512')
    print(token)
    return token

def create_authorization(request_method,url,ak,sk):
    #TIMESTAMP = '1705052797'
    TIMESTAMP = str(int(datetime.now().timestamp()))
    NONCE = str(uuid.uuid4())
    #NONCE = "c278f7c2-3c71-4bed-b5c1-57eb173d8d64"
    data_to_sign = f"{request_method}\n{url.lower()}\n{TIMESTAMP}\n{NONCE}\n"
    print(data_to_sign)
    SK_bytes = sk.encode('utf-8')
    SIGN_bytes = data_to_sign.encode('utf-8')
    digest = hmac.new(SK_bytes, SIGN_bytes, hashlib.sha256).digest()
    signature = base64.b64encode(digest).decode('utf-8')
    result = f'ROC-HmacSHA256-1.0 {ak},{TIMESTAMP},{NONCE},{signature}'
    return result
